<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Places_model extends MY_Model {
	
	public function __construct() {
		$this->_table = 'places';
		parent::__construct();
	}
    
    public function get_karaoke_places($min_lat, $max_lat, $min_lng, $max_lng, $city = '') {
        if (! $min_lat || ! $max_lat || ! $min_lng || ! $max_lng) {
            return false;
        }
        
        $city_where = '';
        if ($city) {
            $city_where = "AND provinceid = '".$city."'";
        }
        
        $this->db->where("latitude >= $min_lat AND latitude <= $max_lat AND longitude >= $min_lng "
            . " AND longitude <= $max_lng $city_where");
        
        $this->db->order_by('latitude, longitude', 'ASC');
        
        return $this->db->get($this->_table);
    }
    
    public function get_by_name($name) {
        if (empty ($name)) {
            return false;
        }
        $this->db->where('nameid', $name);
        return $this->db->get($this->_table);
    }
    
    public function distance ( $latitudeFrom, $longitudeFrom, 
        $latitudeTo, $longitudeTo, $earthRadius = 6371000) {
        // convert from degrees to radians
        $latFrom = deg2rad($latitudeFrom);
        $lonFrom = deg2rad($longitudeFrom);
        $latTo = deg2rad($latitudeTo);
        $lonTo = deg2rad($longitudeTo);

        $lonDelta = $lonTo - $lonFrom;
        $a = pow(cos($latTo) * sin($lonDelta), 2) +
          pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2);
        $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta);

        $angle = atan2(sqrt($a), $b);
        return round(($angle * $earthRadius) / 1000, 2);
    }
}